package com.cqc.listviewchoicedemo;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.cqc.listviewchoicedemo.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${cqc} on 2017/3/13.
 */

public class SampleSingleChoiceActivity extends AppCompatActivity {

    private Context context = this;
    private ListView listView;
    private Button btn;
    private List<String> dataList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_single_choice);
        initData();
        findViews();
        initViews();
    }

    private void initData() {
        for (int i = 0; i < 100; i++) {
            dataList.add("item" + i);
        }
    }

    private void initViews() {
        //设置单选模式有2种方法：xml和java设置
        //        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(SampleSingleChoiceActivity.this, android.R.layout.simple_list_item_single_choice, dataList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String text = (String) listView.getItemAtPosition(position);
                ToastUtil.showShortToast(context, "position=" + position + "\ntext=" + text);
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //单选获取选中的position
                int checkedItemPosition = listView.getCheckedItemPosition();//选中的item的position
                ToastUtil.showShortToast(context, "position=" + checkedItemPosition);
            }
        });
    }

    private void findViews() {
        listView = (ListView) findViewById(R.id.listView);
        btn = (Button) findViewById(R.id.btn);
    }

}
